package com.fingard.dsp.bank.directbank.citic43;

import com.fingard.constant.Format;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import net.sf.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.citic43.CITIC43Util.StrZipUtil;
import com.fingard.net.WebRequest;

public class CITIC43Base extends DirectBase implements ITcpClient {
    protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID,BANKREQBATCHNO) values (?,?,?,?,?,?);";
    protected static final String SELECTSEQ = "SELECT BANKREQSEQID,BANKREQBATCHNO FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";

    protected static String fieldUnionChar = "|";
    protected static String lineUnionChar = "\r\n";
    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getCharset() {
        return getBankConfig().getCharset("gbk");
    }

    protected static final String encodeSha1(String s) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            MessageDigest digest =
                    MessageDigest.getInstance("SHA-1");
            digest.update(s.getBytes());
            byte[] messageDigest = digest.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    protected static String signMsg(Map<String, String> p_signFieldValue) {
        StringBuilder sb = new StringBuilder();
        sb.append("batchNo=" + p_signFieldValue.get("batchNo") + "&");
        sb.append("bizCode=" + p_signFieldValue.get("bizCode") + "&");
        sb.append("countItems=" + p_signFieldValue.get("countItems") + "&");
        sb.append("filename=" + p_signFieldValue.get("fileName") + "&");
        sb.append("fileContent=" + p_signFieldValue.get("fileContent") + "&");
        sb.append("merchantId=" + p_signFieldValue.get("merchantId") + "&");
        sb.append("signType=" + p_signFieldValue.get("signType") + "&");
        sb.append("sumAount=" + p_signFieldValue.get("sumAmount") + "&");
        sb.append("orderDate=" + p_signFieldValue.get("orderDate") + "&");
        sb.append("orderTime=" + p_signFieldValue.get("orderTime") + "&");
        sb.append("version=" + p_signFieldValue.get("version") + "&");
        sb.append("key=" + p_signFieldValue.get("key"));
        //System.out.println("批量代发CITIC43签名结果==" + encodeSha1(StrZipUtil.string2Unicode(sb.toString())));
        return encodeSha1(StrZipUtil.string2Unicode(sb.toString()));
    }

    protected static String returnSignMsgCheck(Map<String, String> retData) {
        //batchNo,bizCode,errCode,fileName,merchantId,respDate,respTime,signType,version,key
        StringBuilder sb = new StringBuilder();
        sb.append("batchNo=" + retData.get("batchNo") + "&");
        sb.append("bizCode=" + retData.get("bizCode") + "&");
        sb.append("errCode=" + retData.get("errCode") + "&");

        sb.append("filename=" + retData.get("fileName") + "&");
        sb.append("merchantId=" + retData.get("merchantId") + "&");
        sb.append("respDate=" + retData.get("respDate") + "&");
        sb.append("respTime=" + retData.get("respTime") + "&");
        sb.append("signType=" + retData.get("signType") + "&");
        sb.append("version=" + retData.get("version") + "&");
        sb.append("key=" + retData.get("key"));
        //System.out.println(sb.toString());
        //System.out.println(encodeSha1(sb.toString()));
        return encodeSha1(sb.toString());
    }

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected static String querySignMsg(Map<String, String> data) {
        StringBuilder sb = new StringBuilder();
        sb.append("batchNo=" + data.get("batchNo") + "&");
        sb.append("bizCode=" + data.get("bizCode") + "&");
        sb.append("filename=" + data.get("fileName") + "&");
        sb.append("merchantId=" + data.get("merchantId") + "&");
        sb.append("signType=" + data.get("signType") + "&");
        sb.append("orderDate=" + data.get("orderDate") + "&");
        sb.append("orderTime=" + data.get("orderTime") + "&");
        sb.append("version=" + data.get("version") + "&");
        sb.append("key=" + data.get("key"));
        //System.out.println(sb.toString());
        return encodeSha1(StrZipUtil.string2Unicode(sb.toString()));
    }

    protected String[] sendToBank(String reqData, String reqUrl) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交银行的地址：" + reqUrl);
        String charsetName = getCharset();
        WriteBankLogLn("2.提交银行的原文：" + reqData);
        reqData = StrZipUtil.string2Unicode(reqData);
        WriteBankLogStep2(reqData);

        //发送银行前置
        WebRequest tmpRequest = new WebRequest(reqUrl);
        tmpRequest.setRequestProperty("accept", "*/*");
        tmpRequest.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
        tmpRequest.setRequestProperty("connection", "Keep-Alive");
        tmpRequest.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        String charName = getCharset();
        byte[] tmpWriteBytes = reqData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charName);
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }


    //tcp格式
    protected String[] sendToBank(String xml) throws Exception {
        WriteBankLogLn("发送给银行的报文：" + xml);
        WriteBankUrlLogLn(bankFront.getIpPortOrUrl());
        String[] result = {"", ""};
        TcpPortClient client = new TcpPortClient(bankFront.serverIP, Integer.valueOf(bankFront.serverPort), this);
        TcpReceiver receiver = client.sendMessage(xml, getCharset());
        result[0] = receiver.connState;
        result[1] = receiver.getFullString(getCharset());
        WriteBankLogStep3(result[1]);
        if (StringHelper.hasAnyChar(result[1]) && result[1].contains("<?xml")) {
            result[1] = result[1].substring(result[1].indexOf("<?xml"));
        }
        return result;
    }

    protected void writeCommonHeader(CITIC43Header header, StringBuilder sbMsg) throws Exception {
        sbMsg.append(header.head);
        if (StringHelper.hasAnyChar(header.transSeq)) {
            sbMsg.append(header.transSeq).append(fieldUnionChar);
        } else {
            sbMsg.append(Format.DateTime14Format.format(new Date()));
            sbMsg.append(StringHelper.padLeft("1", 6, '0')).append(fieldUnionChar);
        }
        sbMsg.append(header.serviceId).append(fieldUnionChar);
    }

    protected static Map<String, String> json2Map(String p_strJson, String p_fieldName) {
        Map<String, String> retMap = new HashMap();
        JSONObject json = JSONObject.fromObject(p_strJson);
        String[] fileds = p_fieldName.split(",");
        for (String name : fileds) {
            if (json.containsKey(name)) {
                retMap.put(name, json.getString(name));
            } else {
                retMap.put(name, null);
            }
        }
        return retMap;
    }

    public String addCharLeft(int length, char c, String str) throws Exception {
        StringBuilder sb = new StringBuilder();
        int strLength = str.getBytes("UTF-8").length;
        for (int i = 0; i < length - strLength; i++) {
            sb.append(c);
        }
        sb.append(str);
        return sb.toString();
    }
    public String addCharRight(int length, char c, String str) throws Exception {
        StringBuilder sb = new StringBuilder();
        int strLength = str.getBytes("UTF-8").length;
        sb.append(str);
        for (int i = 0; i < length - strLength; i++) {
            sb.append(c);
        }
        return sb.toString();
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = "UTF-8";
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</ROOT>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
